package com.file.parser;

import com.file.bo.ResponseData;
import com.file.bo.mail.CMBC2;
import com.file.bo.mail.CMBCTran2;
import com.file.constant.ErrorCode;
import com.file.parser.traprange.PDFTableExtractor;
import com.file.util.JsonUtils;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 民生银行pdf流水解析（新版本表头字段包含中英文, 交易字段不包含"凭证类型"、"凭证号码"、"对方户名/账号"、"对方行名"、"交易机构"字段版本）
 * @author anyspa
 */

@Slf4j
public class CMBCPdfParser2 extends BasePdfParser {

    private static final Integer CMBC2_PDF_HEADER_LINE_NUMBER = 8;
    private static final Integer CMBC2_PDF_FOOTER_LINE_NUMBER = 1;

    public ResponseData<String> parseCMBCPdfToJson(String daId, String filePath) {
        log.info("parseCMBCPdfToJson2 started, daId:{}", daId);
        String json = null;

        try {
            CMBC2 cmbc = parseCMBCPdf(filePath);
            json = JsonUtils.convertObjectToJson(cmbc);
        } catch (Exception e) {
            log.error("OnError|{}||{}|{}|{}|{}", ErrorCode.FILE_PARSE_EXCEPTION.getCode(), daId, "", "", "parseCMBCPdfToJson2 failed", e);
            return new ResponseData<>(json, ErrorCode.FILE_PARSE_EXCEPTION.getCode(),
                    ErrorCode.FILE_PARSE_EXCEPTION.getMsg());
        }

        log.info("parseCMBCPdfToJson2 completed, daId:{}", daId);
        return new ResponseData<>(json, ErrorCode.SUCCESS.getCode(), ErrorCode.SUCCESS.getMsg());
    }

    private CMBC2 parseCMBCPdf(String filePath) {
        CMBC2 cmbc = parseCMBCHeader(filePath);

        List<CMBCTran2> cmbcTrans = parseCmbcTrans(filePath);
        cmbc.setCmbcTrans(cmbcTrans);
        log.info("cmbc2 = " + cmbc);
        return cmbc;
    }

    private CMBC2 parseCMBCHeader(String filePath) {
        CMBC2 cmbc = new CMBC2();
        String pdfHeaderText = parsePdfHeaderText(filePath);
        String customerName = pdfHeaderText.substring(pdfHeaderText.indexOf("客户姓名Name:") + 9,
                pdfHeaderText.indexOf("客户账号Card/Passbook NO")).trim();
        String customerAccount = pdfHeaderText.substring(pdfHeaderText.indexOf("客户账号Card/Passbook NO:") + 21,
                pdfHeaderText.indexOf("币种Currency")).trim();
        String currency = pdfHeaderText.substring(pdfHeaderText.indexOf("币种Currency:") + 11,
                pdfHeaderText.indexOf("账户账号Account NO")).trim();
        String accountNo = pdfHeaderText.substring(pdfHeaderText.indexOf("账户账号Account NO:") + 15,
                pdfHeaderText.indexOf("开户机构Sub Branch")).trim();
        String accountOpeningInstitution = pdfHeaderText.substring(pdfHeaderText.indexOf("开户机构Sub Branch:") + 15,
                pdfHeaderText.indexOf("证件号码ID NO")).trim();
        String idNo = pdfHeaderText.substring(pdfHeaderText.indexOf("证件号码ID NO:") + 10,
                pdfHeaderText.indexOf("起止日期Start-End Date")).trim();
        String transDetailPeriod = pdfHeaderText.substring(pdfHeaderText.indexOf("起止日期Start-End Date:") + 19,
                pdfHeaderText.indexOf("地址Address")).trim();
        String address = pdfHeaderText.substring(pdfHeaderText.indexOf("地址Address:") + 10,
                pdfHeaderText.indexOf("交易时间")).trim();

        cmbc.setCustomerName(customerName);
        cmbc.setCustomerAccount(customerAccount);
        cmbc.setCurrency(currency);
        cmbc.setAccountNo(accountNo);
        cmbc.setAccountOpeningInstitution(accountOpeningInstitution);
        cmbc.setIdNo(idNo);
        cmbc.setTransDetailPeriod(transDetailPeriod);
        cmbc.setAddress(address);
        return cmbc;
    }

    private List<CMBCTran2> parseCmbcTrans(String filePath) {
        List<CMBCTran2> cmbcTrans = new ArrayList<>();
        String transText = parseTransToText(filePath);

        if (Strings.isNullOrEmpty(transText)) {
            return cmbcTrans;
        }
        List<List<String>> tranFieldsList = parseTransTextToTranFieldsList(transText);
        parseTranFieldsListToCMBCTrans(tranFieldsList, cmbcTrans);

        return cmbcTrans;
    }

    private void parseTranFieldsListToCMBCTrans(List<List<String>> tranFieldsList, List<CMBCTran2> cmbcTrans) {
        for (List<String> strings : tranFieldsList) {
            if (Objects.nonNull(strings) && !strings.isEmpty()) {
                if (StringUtils.isNotBlank(strings.get(0)) && strings.get(0).contains("交易时间")) {
                    continue;
                }
                if (StringUtils.isNotBlank(strings.get(0)) && strings.get(0).contains("Transaction Time")) {
                    continue;
                }

                if (StringUtils.isNotBlank(strings.get(0))) {
                    // 正常情况下是6个column
                    if (strings.size() == 6) {
                        CMBCTran2 cmbcTran = new CMBCTran2();
                        cmbcTran.setTransactionTime(strings.get(0));
                        cmbcTran.setSummary(strings.get(1));
                        cmbcTran.setTransactionAmount(strings.get(2));
                        cmbcTran.setBalance(strings.get(3));
                        cmbcTran.setCashTransfer(strings.get(4));
                        cmbcTran.setTransactionChannel(strings.get(5));
                        cmbcTrans.add(cmbcTran);
                    }
                    // 6个column全部粘到一起了
                    // 2022/07/04 11:01:57财付通-快捷支付-手机充值-200.00261.11转账跨行支付
                    else if (strings.size() == 1) {
                        CMBCTran2 cmbcTran = parseRowTran(strings.get(0));
                        if (cmbcTran != null) {
                            cmbcTrans.add(cmbcTran);
                        }
                    }
                }
            }
        }
    }

    private CMBCTran2 parseRowTran(String tran) {
        CMBCTran2 cmbcTran = null;
        // 2022/07/04 11:01:57财付通-快捷支付-手机充值-200.00261.11
        Pattern pattern = Pattern.compile("\\d{4}/\\d{2}/\\d{2}\\s\\d{2}:\\d{2}:\\d{2}\\S*-?(\\d{1,3}(,\\d{3})*)(\\.\\d{2})(\\d{1,3}(,\\d{3})*)(\\.\\d{2})");
        Matcher matcher = pattern.matcher(tran);
        if (matcher.find()) {
            cmbcTran = new CMBCTran2();
            // 转账跨行支付
            String lastTwoColumn = tran.substring(matcher.end());
            cmbcTran.setTransactionTime(tran.trim().substring(0, 19));

            // 财付通-快捷支付-手机充值-200.00261.11
            String columnAfterTransactionTime = tran.trim().substring(19, matcher.end());
            pattern = Pattern.compile("-?(\\d{1,3}(,\\d{3})*)(\\.\\d{2})(\\d{1,3}(,\\d{3})*)(\\.\\d{2})");
            matcher = pattern.matcher(columnAfterTransactionTime);
            if (matcher.find()) {
                cmbcTran.setSummary(columnAfterTransactionTime.substring(0, matcher.start()));

                // -200.00261.11
                String columnAfterSummary = columnAfterTransactionTime.substring(matcher.start());
                pattern = Pattern.compile("-?(\\d{1,3}(,\\d{3})*)(\\.\\d{2})");
                matcher = pattern.matcher(columnAfterSummary);
                if (matcher.find()) {
                    cmbcTran.setTransactionAmount(matcher.group());
                    cmbcTran.setBalance(columnAfterSummary.substring(matcher.end()));
                }
            }

            // 处理最后两个column "现转标志" 和 "交易渠道"
            parseLastTwoColumn(cmbcTran, lastTwoColumn);
        }

        return cmbcTran;
    }

    private void parseLastTwoColumn(CMBCTran2 cmbcTran, String lastTwoColumn) {
        if (StringUtils.isNotBlank(lastTwoColumn)) {
            // 从现有的民生银行pdf文件来看, "现转标志"都是"转账", 后面出现其他的字典再补充
            if (lastTwoColumn.trim().startsWith("转账")) {
                cmbcTran.setCashTransfer("转账");
                cmbcTran.setTransactionChannel(lastTwoColumn.substring(lastTwoColumn.indexOf("转账") + 2));
            } else {
                cmbcTran.setCashTransfer(StringUtils.EMPTY);
                cmbcTran.setTransactionChannel(lastTwoColumn);
            }
        } else {
            cmbcTran.setCashTransfer(StringUtils.EMPTY);
            cmbcTran.setTransactionChannel(StringUtils.EMPTY);
        }
    }


    private String parseTransToText(String filePath) {
        PDFTableExtractor extractor = (new PDFTableExtractor()).setSource(filePath);
        int pdfPageNumber = getPdfPageNumber(filePath);

        // 处理 header
        for (int i = 0; i < pdfPageNumber; i++) {
            int[] headerSkipLines = new int[CMBC2_PDF_HEADER_LINE_NUMBER];
            for (int k = 0; k < CMBC2_PDF_HEADER_LINE_NUMBER; k++) {
                headerSkipLines[k] = k;
            }

            int[] footerSkipLines = new int[CMBC2_PDF_FOOTER_LINE_NUMBER];
            for (int j = 0; j < CMBC2_PDF_FOOTER_LINE_NUMBER; j++) {
                footerSkipLines[j] = -(j + 1);
            }
            extractor.exceptLine(i, headerSkipLines);
            extractor.exceptLine(i, footerSkipLines);
        }
        return extractPdfToText(extractor);
    }

    public static void main(String[] args) {
        CMBCPdfParser2 cmbcPdfParser = new CMBCPdfParser2();
        String json = cmbcPdfParser.parseCMBCPdfToJson("", "D:\\data\\files\\CMBC\\zd4gujg61577132004024164352_acbf4bbb179c21bbfe225f4005045514_beehive-cmbc_jyls-0.pdf").getData();
        System.out.println(json);
    }
}
